<template>
  <div>
    <Table
      ref="tableRef"
      :url="URL_PAGINGTICKETRECORD"
      :columns="data.columns"
      :toolbar="data.toolbar"
      :handles="data.handles"
      :query="data.query"
    ></Table>
    <!-- 弹窗开始 -->
    <el-dialog
      v-model="dialogVisible"
      :title="ruleForm.status === 2 ? '审核通过' : '驳回申请'"
      width="430"
      class="qc-custom-dialog"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="70px"
        class="dialog-form-wrap"
      >
        <el-form-item label="开票信息" v-if="ruleForm.status === 2">
          <el-input
            v-model.trim="ruleForm.reason"
            placeholder="请输入开票信息"
            maxlength="200"
            type="textarea"
            :rows="3"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item
          label="驳回原因"
          prop="reason"
          v-if="ruleForm.status === 1"
        >
          <el-input
            v-model.trim="ruleForm.reason"
            placeholder="请输入驳回原因"
            maxlength="200"
            type="textarea"
            :rows="3"
            show-word-limit
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hide">取消</el-button>
          <el-button type="primary" v-btnAntiShake="onSubmit"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 弹窗结束 -->
  </div>
</template>
  
<script lang="ts" setup name="invoicingApprovalList">
import type { FormInstance, FormRules } from 'element-plus';
import Table from '@/components/table/index.vue';
import { queryDicByParent } from '@/service/apis/api';
import {
  URL_PAGINGTICKETRECORD,
  ticketApprove,
  EXPORT_TICKETRECORD,
} from '@/service/apis/financial';
import { exportFile } from '@/utils/utils';

const router = useRouter();

const tableRef = ref();

const emit = defineEmits(['get-update']);
onActivated(() => {
  emit('get-update', (flag: boolean) => {
    if (flag) {
      tableRef.value?.getData();
    }
  });
});

let dialogVisible = ref(false);

const data = reactive({
  // dialogVisible: false,
  shareProfitId: '',
  formData: {} as any,
  columns: [
    {
      prop: 'createBy',
      label: '申请用户',
    },
    {
      prop: 'powerAmount',
      label: '电费',
    },
    {
      prop: 'serviceAmount',
      label: '服务费',
    },
    {
      prop: 'occupyAmount',
      label: '超时占用费',
    },
    {
      prop: 'ticketType',
      label: '发票形式',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'companyName',
      label: '发票抬头',
    },
    {
      prop: 'taxNumber',
      label: '税号',
    },
    {
      prop: 'bankName',
      label: '开户行名称',
    },
    {
      prop: 'bankAccount',
      label: '开户行账号',
    },
    {
      prop: 'address',
      label: '注册地址',
    },
    {
      prop: 'telephone',
      label: '电话',
    },
    {
      prop: 'createTime',
      label: '申请时间',
    },
    {
      prop: 'status',
      label: '开票状态',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'externalStatusDesc',
      label: '开票状态（第三方）',
      popValue: (row: any, index: any) => {
        if (row.externalReason) {
          return row.externalReason;
        } else {
          return '--';
        }
      },
    },
  ],
  toolbar: [
    {
      label: '导出',
      permission: 'invoicingApprovalList.export',
      icon: 'icon-export',
      type: 'primary',
      plain: true,
      handle: () => {
        exportFile(EXPORT_TICKETRECORD, '开票审批', tableRef.value?.getForm());
      },
    },
  ],
  handles: [
    {
      label: '通过',
      permission: 'invoicingApprovalList.pass',
      disabledFun: (row: any) => {
        return row.status !== 0;
      },
      handle: (row: any) => {
        approve(2, row);
      },
    },
    {
      label: '驳回',
      permission: 'invoicingApprovalList.reject',
      disabledFun: (row: any) => {
        return row.status !== 0;
      },
      handle: (row: any) => {
        approve(1, row);
      },
    },
    {
      label: '详情',
      permission: 'invoicingApprovalList.see',
      handle: (row: any) => {
        router.push({
          name: 'invoicingApprovalDetail',
          query: { id: row.id },
        });
      },
    },
  ],
  query: [
    {
      label: '开票状态',
      prop: 'status',
      comName: 'select',
      props: {
        placeholder: '请选择开票状态',
        options: [] as any,
      },
    },
    {
      label: '手机号',
      prop: 'mobile',
      comName: 'input',
      props: {
        placeholder: '请输入用户手机号',
      },
    },
    {
      label: '申请用户',
      prop: 'applyBy',
      comName: 'input',
      props: {
        placeholder: '请输入申请用户',
      },
    },
    {
      label: '开票形式',
      prop: 'ticketType',
      comName: 'select',
      props: {
        placeholder: '请选择开票形式',
        options: [] as any,
      },
    },
    {
      label: '申请时间',
      prop: 'data',
      comName: 'date',
      keys: ['startTime', 'endTime'],
      props: {
        type: 'daterange',
      },
    },
  ],
});
const ruleForm = reactive({
  reason: '',
  status: 0,
});
const rules = reactive<FormRules>({
  reason: [{ required: true, message: '请输入驳回原因', trigger: 'blur' }],
});

if (import.meta.env.VITE_ENV_TYPE !== 'lznt') {
  data.columns = data.columns.slice(0, data.columns.length - 1);
}

queryDicByParent({ listDtos: ['ticketType', 'ticketRecordStatus'] }).then(
  (res: any) => {
    data.columns[4].dic = [...res.ticketType];
    data.columns[12].dic = [...res.ticketRecordStatus];
    data.query[0].props.options = [...res.ticketRecordStatus];
    data.query[3].props.options = [...res.ticketType];
  }
);
const ruleFormRef = ref<FormInstance>();

// 关闭弹框
const hide = () => {
  dialogVisible.value = false;
};
// 打开弹窗并赋值
const approve = (value: number, row: any) => {
  dialogVisible.value = true;
  ruleForm.reason = '';
  ruleForm.status = value;
  data.formData = row;
  nextTick(() => {
    ruleFormRef.value?.clearValidate();
  });
};

// 充值/退款确认
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  const formData = Object.assign(data.formData, ruleForm);
  ticketApprove(formData).then(() => {
    hide();
    tableRef.value?.handleQuery();
  });
};
</script>